package vip.xiaonuo.invoice.modular.controller;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.invoice.modular.vo.InvoiceDetailVo;


import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 回调测试控制器
 * 用于接收发票系统发送的回调数据
 */
@RestController
@RequestMapping("/callback")
public class CallbackTestController {

    private static final Logger log = LoggerFactory.getLogger(CallbackTestController.class);

    /**
     * 接收发票状态回调 - 增强版本
     * 增加了详细日志、异常处理和请求头信息打印
     */
    @PostMapping("/invoice")

    public ResponseEntity<Map<String, Object>> receiveInvoiceCallback(
            @RequestBody(required = false) InvoiceDetailVo callbackData,
            HttpServletRequest request) {

        // 打印所有请求头，用于调试
        printRequestHeaders(request);

        Map<String, Object> response = new HashMap<>();

        try {
            // 打印接收到的回调数据
            log.info("接收到发票回调请求，URL: {}", request.getRequestURI());

            if (callbackData != null) {
                log.info("回调数据成功解析为InvoiceDetailVo类型: {}", JSON.toJSONString(callbackData, true));

                // 在控制台打印主要信息
                System.out.println("================== 发票回调信息 ==================");
                System.out.println("回调数据: " + JSON.toJSONString(callbackData, true));

                // 打印发票详情信息 - 直接访问InvoiceDetailVo的字段，不再通过Content内部类
                System.out.println("发票跟踪号: " + callbackData.getInvoicedTraceId());
                System.out.println("购方名称: " + callbackData.getBuyerName());
                System.out.println("销方名称: " + callbackData.getSellerName());
                System.out.println("价税合计: " + callbackData.getTotalAmountWithTax());
                System.out.println("===============================================");
            } else {
                log.warn("回调数据无法解析为InvoiceDetailVo类型，可能格式不匹配");
                System.out.println("警告: 回调数据无法解析为InvoiceDetailVo类型");
            }

            // 返回成功响应
            response.put("code", 0);
            response.put("msg", "success");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("处理发票回调失败: {}", e.getMessage(), e);
            System.out.println("错误: 处理回调时发生异常: " + e.getMessage());

            // 返回错误响应
            response.put("code", 500);
            response.put("msg", "处理失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 接收原始回调数据 - 二进制方式，确保能接收到任何格式的数据
     */
    @PostMapping(value = "/invoice/raw", consumes = "*/*")
    public ResponseEntity<Map<String, Object>> receiveInvoiceCallbackRaw(
            @RequestBody byte[] rawData,
            HttpServletRequest request) {

        printRequestHeaders(request);

        Map<String, Object> response = new HashMap<>();
        try {
            String rawDataStr = new String(rawData, "UTF-8");
            log.info("接收到原始回调数据: {}", rawDataStr);

            System.out.println("================== 原始回调数据 ==================");
            System.out.println("Content-Type: " + request.getContentType());
            System.out.println("数据长度: " + rawData.length + " 字节");
            System.out.println("原始数据: " + rawDataStr);
            System.out.println("===============================================");

            // 尝试解析为JSON
            try {
                Object jsonObj = JSON.parse(rawDataStr);
                System.out.println("成功解析为JSON: " + JSON.toJSONString(jsonObj, true));
            } catch (Exception e) {
                System.out.println("无法解析为JSON: " + e.getMessage());
            }

            response.put("code", 0);
            response.put("msg", "success");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("处理原始回调数据失败: {}", e.getMessage(), e);

            response.put("code", 500);
            response.put("msg", "处理失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 打印请求头信息，用于调试
     */
    private void printRequestHeaders(HttpServletRequest request) {
        StringBuilder headersInfo = new StringBuilder("请求头信息:\n");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            headersInfo.append(headerName).append(": ").append(headerValue).append("\n");
        }
        log.debug(headersInfo.toString());
    }
}
